<template>
    <div class="container my-3" >
      <h2>登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input type="text" class="form-control" id="username" v-model="username" required />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input type="password" class="form-control" id="password" v-model="password" required />
        </div>
        <button type="submit" class="btn btn-primary">登录</button>
      </form>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { useStore } from 'vuex';
  import { useRouter } from 'vue-router';
  import { loginApi } from '@/utils/auth';

  const store = useStore();
  const router = useRouter();
  const username = ref('');
  const password = ref('');

  const handleLogin = async () => {
    try {
      const response =await loginApi(username.value, password.value);
      // 检查登录是否成功
      const resData=response.data;
      if (resData.data.token) {
        // 登录成功，存储 token
        localStorage.setItem('authToken', resData.data.token);
        // 获取用户信息（假设登录 API 返回结果中包含用户基本信息）
        const { bio, id, name} = resData.data.user;
        // 将用户信息保存到 Vuex 中
        store.dispatch('saveUserInfo', {  bio,id,name });
        // store.commit('login');
        router.push('/home');
      }
    } catch (error) {
      console.error('登录失败：', error);
    }
  };
  </script>